package main

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"os"
	"reflect"
	"strconv"
	"strings"
	"time"
)

func upload(conn net.Conn, path string) {
	fmt.Println("文件上传开始的路径:", path)
	//打开文件
	uploadFile, _ := os.Open(path)
	fmt.Println("uploadFile", uploadFile)

	//获取上传文件的文件名和大小
	f, _ := os.Stat(path)
	fileSize := f.Size()
	fileName := f.Name()
	fmt.Println("fileSize", fileSize)
	fmt.Println("fileName", fileName)
	Info := "put" + " " + fileName + " " + strconv.FormatInt(fileSize, 10)
	fmt.Println("info::", Info)
	conn.Write([]byte(Info))
	time.Sleep(time.Second)

	reader := bufio.NewReader(uploadFile) //阅读器
	//上传文件内容
	for {
		//读取文件的每一行
		lineContent, err := reader.ReadBytes('\n')
		//发送给服务端
		conn.Write(lineContent)
		if err == io.EOF {
			break
		}
	}
	fmt.Println("文件上传成功！")
}

//文件下载后保存
func download(conn net.Conn, path string) {
	filePath := path
	fmt.Println("下载的文件路径filePath：", filePath) //uploads/2.png
	//文件信息
	fileName := strings.Split(path, "/")[1] //2.png
	fmt.Println("filename:", fileName)

	//fileSize, _ := strconv.Atoi(path[1])
	//fmt.Println("filesize:", fileSize)
	//文件路径发给服务器端
	conn.Write([]byte("get" + " " + filePath))

	data := make([]byte, 1024)
	n, _ := conn.Read(data)
	str01 := string(data[:n])                                //get 2.png 231850
	fmt.Println("服务端传回的文件信息：", str01, reflect.TypeOf(str01)) // get 2.png 231850 string
	byeNum := strings.Split(str01, " ")[2]
	fmt.Println(byeNum, reflect.TypeOf(byeNum)) //231850 string

	fileSize, _ := strconv.Atoi(byeNum)

	//循环接收文件
	file, _ := os.OpenFile("imgs/"+fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 666)
	fmt.Println(file)

	write := bufio.NewWriter(file)

	var readSize = 0
	for readSize < fileSize {
		data := make([]byte, 1024)
		n, _ := conn.Read(data)
		readSize += n
		//将每行数据写到writer中
		write.WriteString(string(data[:n]))
		write.Flush()
	}
	fmt.Println("客户端保存文件成功！")
}

func main() {
	//1、拨号获取客户端的套接字对象，建立连接
	conn, err := net.Dial("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("err:", err)
	}
	fmt.Println(conn)

	//3、客户度发送英文名，服务端转大写后客户端再打印出来
	for {
		//文件上传实现
		reader := bufio.NewReader(os.Stdin) //引导用户输入newreader
		fmt.Print("请输入命令：")
		content, err := reader.ReadString('\n') //读取输入直到换行结束
		if err != nil {
			return
		}
		content = strings.TrimSpace(content) //去掉前后空格
		fmt.Println("读取输入的内容为:", content)

		cmd := strings.Split(content, " ")[0]
		params := strings.Split(content, " ")[1]
		fmt.Println("输入的参数是：", params)

		switch cmd {
		case "put":
			//文件上传
			upload(conn, params) // imgs/1.png
		case "get":
			//文件下载
			download(conn, params) //uploads/2.png
		}
	}

}
